package com.community.listen;

import com.alibaba.fastjson.JSONObject;
import com.community.domain.enity.vo.SendSmsVo;
import com.community.utils.StringUtils;
import com.community.utils.TelSmsUtils;
import com.rabbitmq.client.Channel;
import com.xiaoleilu.hutool.util.RandomUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * 类名称： SendSmsListener
 * 描述： 消息监听者
 * 创建人：zyj
 * 创建时间：2023/11/9 12:23
 */
public class SendSmsListener {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    /**
     * 初始化队列
     * @return
     */
    @Bean
    public org.springframework.amqp.core.Queue initQueue(){
        return new Queue("send.sms",true);
    }

    /**
     * 监听队列
     * @param msg
     * @param message
     * @param channel
     */
    @RabbitListener(queues = "send.sms")
    public void sendSms(String msg, Message message, Channel channel){
        MessageProperties messageProperties = message.getMessageProperties();

        SendSmsVo sendSmsVo = JSONObject.parseObject(msg, SendSmsVo.class);
        String msgId =(String)redisTemplate.opsForValue().get("sms_id:" + sendSmsVo.getMsgId());

        try {
            // 是否被消费
            if(StringUtils.isNoneEmpty(msgId)){
                // 确认签收，不重回队列
                channel.basicAck(messageProperties.getDeliveryTag(),false);
                return;
            }
            // 生成验证码
            String code = RandomUtil.randomNumbers(6);
            HashMap<String, String> map = new HashMap<>();
            map.put(sendSmsVo.getPhone(),code);

            // 发送验证码
            TelSmsUtils.sendSms(sendSmsVo.getPhone(),"code",map);
            // redis存储验证码
            redisTemplate.opsForValue().set("tel_code:" + sendSmsVo.getPhone(),code,15, TimeUnit.MINUTES);
            // 确认签收，不重回队列
            channel.basicAck(messageProperties.getDeliveryTag(),false);

        } catch (Exception o) {
            // 确认没签收，重回队列
            try {
                channel.basicNack(messageProperties.getDeliveryTag(),false,true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}
